<!-- views/LoginView.vue -->
<template>
  <div class="anime-login-container">
    <!-- CSS樱花背景 -->
    <div class="sakura-fall">
      <div v-for="i in 30" :key="i" class="sakura-petal" :style="`--index: ${i}`"></div>
    </div>

    <div class="anime-login-card">
      <!-- 二次元角色 -->
      <div class="anime-character">
        <div class="speech-bubble">欢迎回来，主人~</div>
      </div>

      <!-- 登录表单 -->
      <el-form
          ref="loginForm"
          :model="form"
          :rules="rules"
          class="anime-form"
      >
        <h2 class="form-title">管理后台登录</h2>

        <el-form-item prop="username">
          <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              class="anime-input"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              class="anime-input"
              show-password
          />
        </el-form-item>

        <el-form-item prop="code" style="margin-bottom: 25px;">
          <div style="display: flex; height: 42px;">
            <div style="flex: 2">
              <el-input
                  style="padding: 5px 0;"
                  class="anime-input"
                  prefix-icon="Clock"
                  v-model="form.code"
                  type="text"
                  placeholder="请输入验证码"
              />
            </div>
            <div style="flex: 1;margin-left: 15px">
              <el-image style="width: 120px;height: 100%;" :src="captchaUrl" @click="refreshCaptcha" alt="验证码" class="captcha-img" />
            </div>
          </div>
        </el-form-item>

        <div class="form-actions">
          <el-checkbox v-model="form.remember">记住我</el-checkbox>
          <el-link type="primary" @click="showForgetDialog">忘记密码?</el-link>
        </div>

        <el-button
            type="primary"
            class="anime-button"
            :loading="loading"
            @click="submitForm"
        >
          登录
        </el-button>

        <div class="register-tip">
          没有账号? <el-link type="primary" @click="showPermissionDialog">申请权限</el-link>
        </div>
      </el-form>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog v-model="forgetVisible" title="找回密码">
      <el-form :model="forgetForm" :rules="forgetRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="forgetForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="forgetForm.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="forgetVisible = false">取消</el-button>
        <el-button type="primary" @click="handleForget">提交</el-button>
      </template>
    </el-dialog>

    <!-- 权限申请对话框 -->
    <el-dialog v-model="permissionVisible" title="权限申请">
      <el-form :model="permissionForm" :rules="permissionRules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="permissionForm.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="permissionForm.email" />
        </el-form-item>
        <el-form-item label="申请理由" prop="reason">
          <el-input v-model="permissionForm.reason" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="permissionVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePermission">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import { useRouter } from 'vue-router'
import { ElNotification} from 'element-plus'
import {getCheckCode, login} from "@/api/acconut.js";
import {userInform} from "@/stores/userInform.js";

const router = useRouter()
const userInformPink = userInform()

// 登录表单
const form = reactive({
  username: '',
  password: '',
  code: '',
  cokeKey:'',
  remember: false
})

//获取验证码
const captchaUrl = ref('')
const refreshCaptcha = async () => {
  // 刷新验证码
  const res = await getCheckCode()
  captchaUrl.value = res.data.checkCode
  loginForm.cokeKey = res.data.checkCodeKey
}

// 表单校验规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})

// 忘记密码表单
const forgetVisible = ref(false)
const forgetForm = reactive({
  username: '',
  email: ''
})

const forgetRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
})

// 权限申请表单
const permissionVisible = ref(false)
const permissionForm = reactive({
  name: '',
  email: '',
  reason: ''
})

const permissionRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  reason: [
    { required: true, message: '请输入申请理由', trigger: 'blur' }
  ]
})

const loading = ref(false)
const loginForm = ref(null)

const logKey = {
  username: 'username'
}

// 提交登录表单
const submitForm = () => {
  loginForm.value.validate(async valid => {
    if (valid) {
      loading.value = true
      const res = await login(form)
      if (res.code === 200) {
        if (form.remember) {
          await userInformPink.setUserInformData(res.data.username)
          userInformPink.setToken(res.data.token)
          localStorage.setItem('token', res.data.token) // 写入Cookies
          // 记住密码,将用户名和密码存入localStorage
          localStorage.setItem(logKey.username, form.username)
        }
        ElNotification({
          title: '登录成功',
          message: '欢迎admin',
          type: 'success'
        })
        router.push('/admin')
      } else {
        ElNotification({
          title: '登录失败',
          message: '账号或密码错误，请重新输入',
          type: 'warning'
        })
      }
      loading.value = false
    }
  })
}

// 显示忘记密码对话框
const showForgetDialog = () => {
  forgetVisible.value = true
}

// 处理忘记密码
const handleForget = () => {
  // 调用忘记密码API
    ElNotification({
      title: '邮件发送成功',
      message: '重置链接已发送至您的邮箱',
      type: 'success'
    })
    forgetVisible.value = false
}

// 显示权限申请对话框
const showPermissionDialog = () => {
  permissionVisible.value = true
}

// 处理权限申请
const handlePermission = () => {
  const token = localStorage.getItem("token")
  if(token == null){
    return ElNotification({
      title: '请先登录',
      message: '请先登录再申请权限',
      type: 'warning',
      duration: 3000
    })
  }else{
    // 调用权限申请API
    ElNotification({
      title: '申请已提交',
      message: '管理员将尽快处理',
      type: 'success'
    })
  }
  permissionVisible.value = false
}

onMounted(() => {

  refreshCaptcha()

  //获取本地存储的用户名和密码
  const username = localStorage.getItem(logKey.username)
  if (username) {
    form.username = username
    form.remember = true
  }

  //设置樱花效果
  // 设置一组随机变量
  const root = document.documentElement
  root.style.setProperty('--random-seed', Math.random())
  // 设置一组全局随机变量
  root.style.setProperty('--random-x-start', Math.random() * 100)
  root.style.setProperty('--random-x-end', Math.random() * 100)
  root.style.setProperty('--random-y-start', Math.random() * 20)
  root.style.setProperty('--random-size', Math.random() * 0.7 + 0.3)
  root.style.setProperty('--random-opacity', Math.random() * 0.5 + 0.3)
  root.style.setProperty('--random-duration', Math.random() * 15 + 10)
  root.style.setProperty('--random-delay', Math.random() * 10)
})
</script>

<style lang="css" scoped>
/* 二次元风格样式 */
.anime-login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #ffeef8 100%);
  position: relative;
  overflow: hidden;
  font-family: 'M PLUS Rounded 1c', sans-serif;
}

.anime-login-card {
  position: relative;
  z-index: 10;
  background: white;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(255, 105, 180, 0.2);
  width: 400px;
  padding: 40px;
}

.anime-character {
  text-align: center;
  margin-bottom: 30px;
}

.character-img {
  width: 120px;
  height: 120px;
  object-fit: contain;
  filter: drop-shadow(0 5px 10px rgba(255, 105, 180, 0.3));
}

.speech-bubble {
  display: inline-block;
  background: #ff9ff3;
  color: white;
  padding: 8px 15px;
  border-radius: 20px;
  font-size: 14px;
  margin-top: 10px;
  position: relative;
}

.speech-bubble::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  border-width: 10px 10px 0;
  border-style: solid;
  border-color: #ff9ff3 transparent;
}

.form-title {
  text-align: center;
  color: #ff6b6b;
  margin-bottom: 25px;
  font-size: 24px;
  font-weight: 700;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.register-tip {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.anime-button {
  width: 100%;
  background: linear-gradient(45deg, #ff6b6b, #ff9ff3);
  border: none;
  border-radius: 10px;
  color: white;
  font-weight: bold;
  box-shadow: 0 4px 15px rgba(255, 105, 180, 0.4);
}

@keyframes float {
  0%, 100% { transform: translateY(0) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(5deg); }
}

/* 新增CSS樱花效果 */
.sakura-fall {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
  overflow: hidden;
}

.sakura-petal {
  position: absolute;
  background: radial-gradient(circle, #ffc0cb 30%, transparent 70%);
  border-radius: 50% 0 50% 50%;
  opacity: 0.8;
  filter: drop-shadow(0 0 5px rgba(255, 192, 203, 0.5));
  animation: fall linear infinite;
}

.sakura-petal:nth-child(3n) {
  background: radial-gradient(circle, #ffb6c1 30%, transparent 70%);
}

.sakura-petal:nth-child(3n+1) {
  background: radial-gradient(circle, #ff69b4 30%, transparent 70%);
}

.sakura-petal:nth-child(3n+2) {
  background: radial-gradient(circle, #ffc0cb 30%, transparent 70%);
}

/* 飘落动画关键帧 */
@keyframes fall {
  0% {
    transform: translate(0, 0) rotate(0deg) scale(var(--random-size));
    opacity: 0;
  }
  10% {
    opacity: var(--random-opacity);
  }
  90% {
    opacity: var(--random-opacity);
  }
  100% {
    /* 水平移动：从初始位置到终点位置 */
    transform: translate(calc((var(--random-x-end) - var(--random-x-start)) * 1vw), 100vh) /* 旋转360度增加动态感 */ rotate(360deg) /* 保持初始大小 */ scale(var(--random-size));
    opacity: 0;
  }
}
/* 樱花花瓣基础样式 */
.sakura-petal {
  position: absolute;
  background: radial-gradient(circle, #ffc0cb 30%, transparent 70%);
  border-radius: 50% 0 50% 50%;
  filter: drop-shadow(0 0 5px rgba(255, 192, 203, 0.5));
  animation: fall linear infinite;

  /* 动态属性（通过JS设置） */
  left: calc(var(--random-x-start) * 1%);
  top: calc(var(--random-y-start) * -1vh);
  width: calc(var(--random-size) * 20px);
  height: calc(var(--random-size) * 20px);
  opacity: var(--random-opacity);
  animation-duration: calc(var(--random-duration) * 1s);
  animation-delay: calc(var(--random-delay) * 1s);
}
</style>
